﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VINETLIFE.BL;
using System.Net.Mail;
using System.Xml.Linq;
using System.Data;
using VINETLIFE.DO;

namespace VINETLIFE.Module
{
    public partial class ShopCart : System.Web.UI.UserControl
    {
        cmsProductBL data = new cmsProductBL();
        string strFromMail = "";
        string strFromPass = "";
        string strToMail = "";
        string strDisplay = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadMail();
                if (Request.QueryString["Id"] != null)
                {
                    if (Session["shop"] == null)
                    {
                        Session["shop"] = new MyShopCart();
                    }
                    //AddItem();
                }
                ShowData();
            }
        }

        private void AddItem()
        {
            cmsProductDO itemDO = new cmsProductDO();
            itemDO.ProductID = Convert.ToInt32(Request.QueryString["Id"]);
            cmsProductDO product = data.Select(itemDO);
            if (product != null)
            {
                ProductShop item = new ProductShop();
                item.Id = product.ProductID;
                item.Image = product.ProductImage;
                item.Name = product.ProductTitle;
                if (product.Price == null || product.Price.ToString() == "")
                    item.Cost = 0;
                else
                    item.Cost = (decimal)product.Price;
                item.Quantity = 1;

                ((MyShopCart)Session["shop"]).Add(item);
            }
        }


        private void ShowData()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Id");
            table.Columns.Add("Name");
            table.Columns.Add("Cost");
            table.Columns.Add("Image");
            table.Columns.Add("Quantity");
            table.Columns.Add("TotalCost");
            if (Session["shop"] != null)
            {
                foreach (var item in ((MyShopCart)Session["shop"]).ListProduct)
                {

                    DataRow row = table.NewRow();
                    row["Id"] = item.Id;
                    row["Name"] = item.Name;
                    if (item.Cost == null)
                    {
                        String.Format("{0:0,0}", 0);
                    }
                    else
                    {
                        row["Cost"] = String.Format("{0:0,0}", item.Cost);
                    }
                    row["Image"] = item.Image;
                    row["Quantity"] = item.Quantity;
                    row["TotalCost"] = String.Format("{0:0,0}", item.Quantity * item.Cost);

                    table.Rows.Add(row);
                }

                GridView1.DataSource = table;
                GridView1.DataBind();
            }
            else
            {
                btnSend.Visible = false;
                btnUpdate.Visible = false;
                btnDel.Visible = false;
            }

            
            if (Session["shop"] != null)
            {
                decimal totalCost = ((MyShopCart)Session["shop"]).GetTotalCost();
                ltTongTien.Text = String.Format("{0:0,0}", totalCost) + " VNĐ";

                string longCost = String.Format("{0:0}", totalCost);
                ClsDocTien cls = new ClsDocTien();
                ltTongTienChu.Text = cls.DocTien(Convert.ToInt64(longCost), " đồng");
            }
        }

        private void LoadMail()
        {
            try
            {
                cmsProductBL productData = new cmsProductBL();
                XElement xml = XElement.Load(MyConfig.serverPath + "Mail.xml");
                XElement mailFromName = xml.Descendants("MailFrom").Descendants("Name").First();
                XElement mailFromPass = xml.Descendants("MailFrom").Descendants("Pass").First();
                XElement mailToName = xml.Descendants("MailTo").Descendants("Name").First();
                XElement mailDisplay = xml.Descendants("Display").Descendants("Name").First();
                strFromMail = mailFromName.Value;
                strFromPass = mailFromPass.Value;
                strToMail = mailToName.Value;
                strDisplay = mailDisplay.Value;
            }
            catch { }
        }


        public bool SendMail(string fromAddress, string fromPassWord, string fromDisplayName, string toAddress, string subject, string body)
        {
            //--Tạo mail -----------------------------------------------------|
            MailMessage msg = new MailMessage();
            msg.To.Add(toAddress);
            msg.From = new MailAddress(fromAddress, fromDisplayName,
                System.Text.Encoding.UTF8);
            msg.Subject = subject;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = body;
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            //--Cho phép gửi mã HTML trong mail ------------------------------|
            msg.IsBodyHtml = true;
            //--Độ ưu tiên của mail ------------------------------------------|
            msg.Priority = MailPriority.High;
            //--Chứng thực bao gồm username + password -----------------------|
            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential
            (fromAddress, fromPassWord);
            //--Cổng 587 của server SMTP Google để gửi mail-------------------|
            client.Port = 587;
            //--Địa chỉ server SMTP của google -------------------------------|
            client.Host = "smtp.gmail.com";
            //--Sử dụng mã hóa đường truyền SSL (Secure Sockets Layer)--------|
            client.EnableSsl = true;
            //--Bắt đầu quá trình gửi mail -----------------------------------|
            try { client.Send(msg); } //--Gửi mail--| 
            catch { return false; } //--Không thể gửi mail     
            return true; //--Gửi mail thành công
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            if (Session["url_back"] == null)
                Response.Redirect("~/");
            else
            {
                Response.Redirect(Session["url_back"].ToString());
            }
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            //ltThongBao.Text = "";
            Response.Redirect("/thanh-toan/");
            //if (Session["Customer"] != null)
            //{
            //    divInfo.Visible = true;
            //    int id = Convert.ToInt32(Session["Customer"]);
            //    cmsCustomerDO objCustomerDO = new cmsCustomerDO();
            //    objCustomerDO.Id = id;
            //    objCustomerDO = new cmsCustomerBL().Select(objCustomerDO);
            //    txtName.Text = objCustomerDO.FullName;
            //    txtAddress.Text = objCustomerDO.Address;
            //    txtEmail.Text = objCustomerDO.Email;
            //    txtPhone.Text = objCustomerDO.Phone;
            //}
            //else
            //    divOrder.Visible = true;
        }
        protected void btnDel_Click(object sender, EventArgs e)
        {
            ltThongBao.Text = "";
            bool del = false;
            foreach (GridViewRow item in GridView1.Rows)
            {
                foreach (Control ctrl in item.Cells[1].Controls)
                {
                    if (ctrl.GetType() == typeof(CheckBox))
                    {
                        CheckBox check = (CheckBox)ctrl;
                        if (check.Checked)
                        {
                            int id = Convert.ToInt32(item.Cells[3].Text.Replace("P", ""));
                            ((MyShopCart)Session["shop"]).Delete(id);
                            del = true;
                        }
                        break;
                    }
                }
            }
            if (del)
                ShowData();
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            ltThongBao.Text = "";
            foreach (GridViewRow item in GridView1.Rows)
            {
                foreach (Control ctrl in item.Cells[6].Controls)
                {
                    if (ctrl.GetType() == typeof(TextBox))
                    {
                        TextBox textBox = (TextBox)ctrl;
                        int id = Convert.ToInt32(item.Cells[3].Text);
                        int quantity;
                        if (!int.TryParse(textBox.Text.Trim(), out quantity))
                        {
                            Myfunction.ThongBao(ltThongBao, "Nhập số lượng không hợp lệ");
                            return;
                        }
                        ((MyShopCart)Session["shop"]).UpdateQuantity(id, quantity);
                        break;
                    }
                }
            }
            ShowData();
        }
        protected void btnOk_Click(object sender, EventArgs e)
        {
            ltThongBao.Text = "";
            //try
            //{
            if (Session["shop"] == null)
            {
                Myfunction.ThongBao(ltThongBao, "Hiện tại chưa có sản phẩm nào ! Vui lòng chọn sản phẩm trước khi gửi !");
                return;
            }

            if (Session["shop"] != null)
            {
                if (((MyShopCart)Session["shop"]).GetTotalProduct() == 0)
                {
                    Myfunction.ThongBao(ltThongBao, "Hiện tại chưa có sản phẩm nào ! Vui lòng chọn sản phẩm trước khi gửi !");
                    return;
                }
            }

            LoadMail();
            if (txtName.Text == "")
            {
                Myfunction.ThongBao(ltThongBao, "Nhập họ tên ! ");
                return;
            }
            if (!Myfunction.isEmailValid(txtEmail.Text))
            {
                Myfunction.ThongBao(ltThongBao, "Nhập email không hợp lệ ! ");
                return;
            }

            DateTime now = DateTime.Now;
            string date = now.Day + " - " + now.Month + " - " + now.Year;

            //ContactBLL data = new ContactBLL();
            //DAL.Contact contact = new DAL.Contact();
            //contact.Address = txtAddress.Text;
            //  contact.Content = txtContent.Text;

            MyShopCart myShop = (MyShopCart)Session["shop"];
            string totalCost = String.Format("{0:0,0}", myShop.GetTotalCost());

            string content = "<div style='margin-top:10px'>";
            content += "<fieldset>";
            content += "<legend>Thông tin đặt hàng</legend>";
            content += " <table width='100%' border='1' cellpadding='3' cellspacing='0' style='border-collapse:collapse'>";
            content += "<tbody><tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Thông tin khách hàng </td></tr>";
            content += "<tr><td style='width:100px'>Họ tên : </td><td>" + txtName.Text + "</td></tr>";
            content += "<tr><td>Địa chỉ : </td><td>" + txtAddress.Text + "</td></tr>";
            content += "<tr><td>Điện thoại : </td><td>" + txtPhone.Text + "</td></tr> ";
            content += "<tr><td>Email : </td><td>" + txtEmail.Text + "</td></tr>";
            content += "<tr><td>Ghi chú : </td><td>" + txtNotes.Text + "</td></tr>";
            content += "<tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Thông tin sản phẩm đặt hàng </td></tr>";
            int count_item = 1;
            foreach (var item in myShop.ListProduct)
            {
                content += "<tr><td style='width:100px'>Sản phẩm " + count_item + "</td><td>" + item.Name + " - Mã : " + item.Id + " - Số lượng : " + item.Quantity + " - Giá : " + String.Format("{0:0,0}", item.Cost) + "</td></tr>";
                count_item++;
            }
            content += "<tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Tổng giá trị : " + totalCost + "</td></tr>";
            content += "</table>";
            content += "<p>Ngày gửi : " + date + "</p></fieldset></div>";

            
            
            //contact.Content = HttpUtility.HtmlEncode(content);
            //contact.DateSend = DateTime.Now;
            //contact.Email = txtEmail.Text;
            //contact.isRead = false;
            //contact.Name = txtName.Text;
            //contact.Phone = txtPhone.Text;
            //contact.Title = "Đặt hàng ngày " + date;
            //data.Add(contact);

            // Send To Mail


            SendMail(strFromMail, strFromPass, strDisplay, strToMail, "Đơn đặt hàng ngày " + now.ToString(), content);
            AddShopcart();
            Session["shop"] = null;
            Reset();
            Myfunction.ThongBao(ltThongBao, "Đặt hàng của bạn đã được gửi ! ");
            //}
            //catch(Exception ex) {
            //    Myfunction.ThongBao(ltThongBao, ex.Message);
            //}
        }

        private void Reset()
        {
            txtPhone.Text = "";
            txtName.Text = "";
            txtEmail.Text = "";
            txtAddress.Text = "";
            txtNotes.Text = "";
        }

        void AddShopcart()
        {
            cmsCustomerBL data = new cmsCustomerBL();
            cmsCustomerDO itemCustomerDO = new cmsCustomerDO();
            cmsOrdersDO itemOrderDO = new cmsOrdersDO();
            cmsOrdersBL dataOrder = new cmsOrdersBL();
            int customerId = 0;
            if (Session["CustomerID"].ToString() != "")
            {
                //Customer
                customerId = Convert.ToInt32(Session["CustomerID"]);
                itemCustomerDO.Id = customerId;
                itemCustomerDO = new cmsCustomerBL().Select(itemCustomerDO);
                itemCustomerDO.Address = itemCustomerDO.Address;
                itemCustomerDO.Brithday = itemCustomerDO.Brithday;
                itemCustomerDO.Email = txtEmail.Text.Trim();
                itemCustomerDO.FullName = txtName.Text.Trim();
                itemCustomerDO.IsEnable = itemCustomerDO.IsEnable;
                itemCustomerDO.IsVangLai = itemCustomerDO.IsVangLai;
                itemCustomerDO.Password = itemCustomerDO.Password;
                itemCustomerDO.Phone = itemCustomerDO.Phone;
                itemCustomerDO.RegisterDay = itemCustomerDO.RegisterDay;
                itemCustomerDO.Sex = itemCustomerDO.Sex;
                itemCustomerDO.UserName = itemCustomerDO.UserName;
                data.Update(itemCustomerDO);
            }
            else
            {
                //Customer
                itemCustomerDO.Address = txtAddress.Text;
                itemCustomerDO.Brithday = Convert.ToDateTime("1/1/1900");
                itemCustomerDO.Email = txtEmail.Text.Trim();
                itemCustomerDO.FullName = txtName.Text.Trim();
                itemCustomerDO.IsEnable = false;
                itemCustomerDO.IsVangLai = true;
                itemCustomerDO.Password = "";
                itemCustomerDO.Phone = txtPhone.Text;
                itemCustomerDO.RegisterDay = Convert.ToDateTime("1/1/1900");
                //itemCustomerDO.Sex = ;
                itemCustomerDO.UserName = "";
                customerId = data.Insert(itemCustomerDO);
            }
                //Order
                itemOrderDO.CreateDate = DateTime.Now;
                itemOrderDO.Address = txtAddress.Text.Trim();
                itemOrderDO.CustomerId = customerId;
                itemOrderDO.DateOfStart = DateTime.Now;
                itemOrderDO.DateOfFisnish = Convert.ToDateTime(txtNgayNhan.Text.Trim());
                itemOrderDO.IsEnable = false;
                itemOrderDO.IsView = false;
                itemOrderDO.Note = txtNotes.Text.Trim();
                itemOrderDO.Phone = txtPhone.Text.Trim();
                itemOrderDO.Status = false;

                int idOrder = dataOrder.Insert(itemOrderDO);

                //OrderDetail
                cmsOrderDetailsDO itemOrderDetailDO = new cmsOrderDetailsDO();
                cmsOrderDetailsBL dataOrderDetail = new cmsOrderDetailsBL();
                foreach (GridViewRow item in GridView1.Rows)
                {
                    foreach (Control ctrl in item.Cells[6].Controls)
                    {
                        if (ctrl.GetType() == typeof(TextBox))
                        {
                            TextBox textBox = (TextBox)ctrl;
                            itemOrderDetailDO.Qty = int.Parse(textBox.Text);
                        }
                    }
                    itemOrderDetailDO.ProductId = Convert.ToInt32(item.Cells[3].Text);
                    itemOrderDetailDO.Price = Convert.ToInt32(item.Cells[5].Text.ToString().Replace(",",""));
                    itemOrderDetailDO.OrderId = idOrder;
                    dataOrderDetail.Insert(itemOrderDetailDO);
                }
            
        }
    }
}